package com.easylinkin.linkappapi.crane.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.easylinkin.linkappapi.common.exceptions.BusinessException;
import com.easylinkin.linkappapi.common.model.RequestModel;
import com.easylinkin.linkappapi.crane.entity.CraneOperationArea;
import com.easylinkin.linkappapi.crane.entity.CraneOperationAreaRefMechanical;
import com.easylinkin.linkappapi.crane.service.ICraneOperationAreaRefMechanicalService;
import com.easylinkin.linkappapi.crane.service.ICraneOperationAreaService;
import com.easylinkin.linkappapi.mechanical.entity.EquipmentLocation;
import com.easylinkin.linkappapi.mechanical.entity.Mechanical;
import com.easylinkin.linkappapi.security.context.LinkappUserContextProducer;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import site.morn.rest.RestBuilders;
import site.morn.rest.RestMessage;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 吊车作业区域表 前端控制器
 *
 * @author xy
 * @since 2025-06-16
 */
@Api(tags = "吊车作业区域表")
@RestController
@RequestMapping("/crane/craneOperationArea")
public class CraneOperationAreaController {
    @Autowired
    private ICraneOperationAreaService craneOperationAreaService;
    @Autowired
    private ICraneOperationAreaRefMechanicalService refMechanicalService;
    @Autowired
    private LinkappUserContextProducer linkappUserContextProducer;

    /**
     * 分页列表查询
     *
     * @param requestModel
     * @return
     */
    @ApiOperation(value="分页列表查询", notes="分页列表查询")
    @PostMapping(value = "/listPage")
    public RestMessage queryPageList(@RequestBody RequestModel<CraneOperationArea> requestModel) {
        // Assert.notNull(requestModel,"参数不能为空");
        // Assert.notNull(requestModel.getCustomQueryParams(), "customQueryParams 不能为空");
        Assert.notNull(requestModel.getPage(), "page 不能为空");
        IPage<CraneOperationArea> pageList = craneOperationAreaService.queryPageList(requestModel);
        return RestBuilders.successBuilder().data(pageList).build();
    }

    /**
     * 保存
     *
     * @param craneOperationArea
     * @return
     */
    @ApiOperation(value="保存", notes="保存")
    @PostMapping(value = "/save")
    public RestMessage save(@RequestBody CraneOperationArea craneOperationArea) {
        setBase(craneOperationArea);
        if(craneOperationArea.getId() != null){
            craneOperationAreaService.updateById(craneOperationArea);
        } else {
            //新增默认关闭
            craneOperationArea.setEnabledFlag(0);
            craneOperationAreaService.save(craneOperationArea);
        }
        // 关联机械设备
        List<Mechanical> mechanicalList = craneOperationArea.getMechanicalList();
        if (CollUtil.isNotEmpty(mechanicalList)) {
            // 先删除原有关联
            refMechanicalService.remove(Wrappers.<CraneOperationAreaRefMechanical>lambdaQuery()
                    .eq(CraneOperationAreaRefMechanical::getOperationAreaId, craneOperationArea.getId()));
            // 再新增关联
            List<CraneOperationAreaRefMechanical> refMechanicalList =
                    mechanicalList.stream().map(mechanical -> {
                        CraneOperationAreaRefMechanical ref = new CraneOperationAreaRefMechanical();
                        ref.setOperationAreaId(craneOperationArea.getId());
                        ref.setMechanicalId(mechanical.getId());
                        setBaseRefMechanical(ref);
                        return ref;
                    }).collect(Collectors.toList());
            refMechanicalService.saveBatch(refMechanicalList);
        }
        // TODO 计算告警
        return RestBuilders.successBuilder().message("保存成功" ).build();
    }

    /**
     * 设置基本属性
     *
     * @param craneOperationArea
     */
    private void setBase(CraneOperationArea craneOperationArea) {
        // 名称唯一校验
        LambdaQueryWrapper<CraneOperationArea> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(CraneOperationArea::getRegionName, craneOperationArea.getRegionName());
        queryWrapper.eq(CraneOperationArea::getTenantId, linkappUserContextProducer.getNotNullCurrent().getTenantId());
        if (craneOperationArea.getId() != null) {
            queryWrapper.ne(CraneOperationArea::getId, craneOperationArea.getId());
        }
        Integer count = craneOperationAreaService.count(queryWrapper);
        if (count > 0) {
            throw new BusinessException("区域名称已存在");
        }
        craneOperationArea.setModifyTime(new Date());
        craneOperationArea.setModifyId(linkappUserContextProducer.getCurrent().getId());
        //没有id就是新增,有就是编辑
        if (null == craneOperationArea.getId()) {
            craneOperationArea.setCreateId(linkappUserContextProducer.getCurrent().getId());
            craneOperationArea.setCreateTime(new Date());
            craneOperationArea.setTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
        }
    }

    private void setBaseRefMechanical(CraneOperationAreaRefMechanical refMechanical) {
        refMechanical.setModifyTime(new Date());
        refMechanical.setModifyId(linkappUserContextProducer.getCurrent().getId());
        //没有id就是新增,有就是编辑
        if (null == refMechanical.getId()) {
            refMechanical.setCreateId(linkappUserContextProducer.getCurrent().getId());
            refMechanical.setCreateTime(new Date());
        }
    }

    /**
     * 启用/禁用
     *
     * @param id
     * @param enabledFlag
     * @return
     */
    @ApiOperation(value="启用/禁用", notes="启用/禁用")
    @PostMapping(value = "/enableOrDisable")
    public RestMessage enableOrDisable(@RequestParam("id") Integer id, @RequestParam("enabledFlag") Integer enabledFlag) {
        CraneOperationArea craneOperationArea = craneOperationAreaService.getById(id);
        if(craneOperationArea == null) {
            return RestBuilders.errorBuilder().message("未找到对应数据").build();
        }
        craneOperationArea.setEnabledFlag(enabledFlag);
        craneOperationAreaService.updateById(craneOperationArea);
        return RestBuilders.successBuilder().message("操作成功").build();
    }


    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @ApiOperation(value="通过id删除", notes="通过id删除")
    @DeleteMapping(value = "/delete")
    public RestMessage delete(@RequestParam("id") Integer id) {
        craneOperationAreaService.removeById(id);
        // 删除关联关系
        refMechanicalService.remove(Wrappers.<CraneOperationAreaRefMechanical>lambdaQuery()
                .eq(CraneOperationAreaRefMechanical::getOperationAreaId, id));
        return RestBuilders.successBuilder().message("删除成功").build();
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @ApiOperation(value="批量删除", notes="批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public RestMessage deleteBatch(@RequestParam("ids") String ids) {
        this.craneOperationAreaService.removeByIds(Arrays.asList(ids.split(",")));
        // 删除关联关系
        refMechanicalService.remove(Wrappers.<CraneOperationAreaRefMechanical>lambdaQuery()
                .in(CraneOperationAreaRefMechanical::getOperationAreaId, Arrays.asList(ids.split(","))));
        return RestBuilders.successBuilder().message("批量删除成功").build();
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @ApiOperation(value="通过id查询", notes="通过id查询")
    @GetMapping(value = "/queryById")
    public RestMessage queryById(@RequestParam("id") Long id) {
        CraneOperationArea craneOperationArea = craneOperationAreaService.queryById(id);
        if(craneOperationArea == null) {
            return RestBuilders.errorBuilder().message("未找到对应数据").build();
        }
        return RestBuilders.successBuilder().data(craneOperationArea).build();
    }
}
